package cn.tb.pet.service.impl;

import cn.tb.pet.domain.PetType;
import cn.tb.pet.mapper.PetTypeMapper;
import cn.tb.pet.service.IPetTypeService;
import cn.tb.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tangbo
 * @since 2022-06-25
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    /**
     * 无限级宠物类型树
     *
     * @return
     */
    @Override
    public List<PetType> petTypeTree() {
        //一次性查询到所有的数据，放在缓存中
        List<PetType> petTypes = petTypeMapper.loadAll();
        Map<Long, PetType> allPetTypes = new HashMap<>();
        for (PetType petType : petTypes) {
            allPetTypes.put(petType.getId(), petType);
        }
        List<PetType> firstPetTypes = new ArrayList<>();
        for (PetType temp : petTypes) {
            if (temp.getPid() == null) {
                //顶级
                firstPetTypes.add(temp);
            } else {
                //不是顶级，找到自己的上级，把自己交给上级的children
                PetType parent = allPetTypes.get(temp.getPid());
                parent.getChildren().add(temp);
            }
        }
        return firstPetTypes;

    }
}
